<template>
    <div id="inst-approval">
        <!-- <span class="title">指令信息</span>
        <el-divider></el-divider> -->
        <div v-if="type === 'first'" style="margin: 6px 0">
            <el-button type="primary" @click="handleShowSetting('start', false)"> 计算</el-button>
            <el-button type="primary" @click="handleShowSetting('approve', false)"> 审核</el-button>
            <el-button type="primary" @click="handleShowSetting('refresh')"> 刷新 </el-button>
            <div style="float: right">
                <div class="auto-select">
                    <!-- <span v-show="existAutoApprove == '1'">
                        自动审批
                    </span>
                    <el-switch
                        size="mini"
                        active-value="1"
                        inactive-value="0"
                        active-color="#409eff"
                        inactive-color="#eee"
                        v-model="isAutoApprove"
                        v-show="existAutoApprove == '1'"
                    ></el-switch> -->
                    <el-button type="primary" size="mini" @click="handleButton('doLayout')" style="margin: 0 16px">布局设置</el-button>
                    <i class="el-icon-setting setting" @click="handleShowSetting('setting')"></i>
                </div>
            </div>
        </div>

        <div v-if="type === 'history'">
            <InstApprovalQueryCondition
                :searchParam="searchParam"
                @handleButton="handleButton"
                :isFirst="type == 'histroy' && isFirst"
            ></InstApprovalQueryCondition>
        </div>
        <div id="main-content">
            <vxe-table
                :cell-style="getCellStyle"
                :row-style="row => getRowStyle(row)"
                :auto-resize="true"
                :data="instDataSourceList"
                border
                size="mini"
                style="width: 100%"
                v-loading="loading"
                resizable
                :resizable-config="{ minWidth: '60' }"
                @cell-click="handleRow"
                @checkbox-change="handleChecked"
                @checkbox-all="handleCheckedAll"
                show-header-overflow
                highlight-current-row
                highlight-hover-row
                :row-config="{ isCurrent: true, isHover: true }"
                ref="xTable1"
                header-align="center"
                :key="approveKey"
            >
                <vxe-column type="checkbox" width="40" align="center" :reserve-selection="true" :fixed="left" v-if="type === 'first'"></vxe-column>
                <vxe-column
                    v-for="item in showFieldList"
                    :key="item.name"
                    :field="item.id"
                    :title="item.content"
                    :min-width="item.minWidth || '100px'"
                    show-overflow="tooltip"
                >
                    <!--  :align="getAlign(item)" -->
                    <template #default="{ row }">
                        <span v-if="item.type == 'func'">
                            {{ item.funcBody(row[item.id], row) || '--' }}
                        </span>
                        <span v-else-if="item.type == 'statusTag'">
                            <StatusTag :code="row[item.id]"></StatusTag>
                        </span>
                        <span v-else-if="item.type == 'status'">
                            {{ item.statusKV[row[item.id]] || '--' }}
                        </span>
                        <span v-else-if="item.id == 'realDirection'">
                            {{ tadeP[row[item.id]] || '--' }}
                        </span>
                        <span v-else-if="item.id == 'marketCode'">
                            {{ marketIdP[row[item.id]] || '--' }}
                        </span>
                        <span v-else-if="item.type == 'branchTag'">
                            <branch-tag :data="row" v-if="row.branchNum && row.branchNum > 0" />
                            <span v-else>--</span>
                        </span>
                        <span v-else>
                            {{ row[item.id] && (row[item.id] + '').trim() ? row[item.id] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>

            <risk-pagination :paging="pageInst" @page-change="pageQueryInst"></risk-pagination>
        </div>

        <span class="title title2">指令结果</span>
        <el-divider></el-divider>
        <div id="bottom-content">
            <div>
                <span
                    >风控结果：
                    <span style="color:red"> <StatusTag :code="resultInfo.result"></StatusTag></span>
                </span>
                <span style="margin-left: 40px"
                    >审核时间：<span style="color: red">{{ resultInfo.date }}</span></span
                >
                <span style="margin-left: 40px"
                    >条目检查数：<span style="color: red">{{ resultInfo.count }}</span></span
                >
            </div>
            <div>
                <el-checkbox v-model="thresholdTypeFilter['1']" @change="handelThresholdTypeFilter">显示触警</el-checkbox>
                <el-checkbox v-model="thresholdTypeFilter['0']" @change="handelThresholdTypeFilter">显示合规</el-checkbox>
            </div>
        </div>

        <div id="main-content">
            <vxe-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :cell-style="getCellStyleResult"
                :row-style="{ height: '35px' }"
                :header-row-style="{ height: '35px', padding: '5px 0' }"
                :key="tableKey"
                :auto-resize="true"
                :data="resultDataSource"
                border
                size="mini"
                style="width: 100%"
                v-loading="resultLoading"
                show-header-overflow
                resizable
                :resizable-config="{ minWidth: '60' }"
                header-align="center"
            >
                <!-- :sort-config="{ defaultSort: { field: 'thresholdType', order: 'desc' }, sortMethod: customSortMethod }" -->
                <vxe-column
                    v-for="item in resultColumns"
                    :key="item.val"
                    :field="item.val"
                    :title="item.name"
                    :min-width="item.minWidth || 100"
                    :column-config="{ isHover: true }"
                    :row-config="{ isHover: true }"
                    show-overflow="tooltip"
                >
                    <!-- :align="getAlignResult(item)" -->
                    <!-- :sortable="item.sortable" -->
                    <!-- :filters="item.filters"
                    :filter-method="item.filterMethod" -->
                    <!-- <template
                        #filter="{ $panel, column }"
                        v-if="['fundCode', 'fundNameSt','assetCode', 'assetName', 'fundAccountCode', 'fundAccountName', 'stockCode', 'stockNameSt', 'entryCode', 'entryName'].includes(item.val)"
                    >
                        <div>
                            <el-input
                                class="my-input"
                                type="type"
                                v-for="(option, index) in column.filters"
                                :key="index"
                                v-model="option.data"
                                @input="$panel.changeOption($event, !!option.data, option)"
                            />
                        </div>
                    </template> -->
                    <template #default="{ row }">
                        <span v-if="item.type == 'func'">
                            {{ item.funcBody(row[item.val], row) || '--' }}
                        </span>
                        <span v-else-if="item.type == 'statusTag'">
                            <StatusTag :code="row[item.val]"></StatusTag>
                        </span>
                        <span v-else-if="item.type == 'branchTag'">
                            <branch-tag :data="row" v-if="row.branchNum && row.branchNum > 0" />
                            <span v-else>--</span>
                        </span>
                        <span v-else-if="['investableBalance', 'maxTradable', 'maxTradableMerge'].includes(item.val)">
                            <el-popover v-if="getObjectLength(row[item.val]) && getObjectLength(row[item.val]) > 1" placement="top" trigger="hover">
                                <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in row[item.val]" :key="key">
                                    {{ '阀值' + ++index + getShowName(item.val) + ': ' + row[item.val][getParamName(item.val) + index] }}
                                </div>
                                <el-tag slot="reference">{{ getObjectLength(row[item.val]) + '个' + getShowName(item.val) }}</el-tag>
                            </el-popover>
                            <span v-else-if="getObjectLength(row[item.val])" v-for="(value, key) in row[item.val]" :key="key">{{ value }}</span>
                            <span v-else> --</span>
                        </span>
                        <span v-else>
                            {{ row[item.val] ? row[item.val] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <RiskPagination :paging="pageResult" @page-change="pageQueryResult"></RiskPagination>
        </div>

        <oneToTwoTranstable
            :resourceCode="resourceCode"
            :selectEntryGroupCode="selectEntryGroupCode"
            :showEntryGroupModal.sync="showEntryGroupModal"
            v-if="showEntryGroupModal"
            @transReturn="transReturn"
        ></oneToTwoTranstable>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="existAutoApprove == '1' ? exitAutoColumns.concat(instColumns) : instColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :table-name="type == 'history' ? 'TN_INST_APPRPVAL_HISTORY' : 'TN_INST_APPRPVAL'"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import RiskTable from '@/common/components/risk-table.vue';
import Invest from '@/common/dict/invest';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { UserModule } from '@/store/modules/user';
import DictionConstUtil from '@/utils/diction-const-util';
import { dateFormat, getCurrentPageData, numberFormat, numberFormatXDAY, timeFormat, UUID, unitShow, getConfigItem } from '@/utils/tools';
import { getActiveMenuCode, getSystem } from '@/utils/user-util';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import oneToTwoTranstable from '../one-to-two-trantable.vue';
import ColumnUtil from '../utils/column-util';
import InstApprovalQueryCondition from './inst-approval-query-condition.vue';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'InstApprovalContent',
    components: {
        RiskTable,
        oneToTwoTranstable,
        StatusTag,
        BranchTag,
        InstApprovalQueryCondition,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class InstApprovalContent extends Vue {
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    ColumnUtil = new ColumnUtil();
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    numberFormatXDAY = numberFormatXDAY;
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    numberFormat = numberFormat;
    unitShow = unitShow;
    Invest = new Invest();

    @Prop() type: string;

    isFirst: boolean = true;

    isAutoApprove: string = (getSystem().find(item => item.paramKey == 'IS_AUTO_APPROVE') || {}).paramValue || false; // 自动审批  0 关闭  1打开

    existAutoApprove: string = (getSystem().find(item => item.paramKey == 'EXISTS_AUTO_APPROVE') || {}).paramValue || false; // 是否存在自动审批

    checkedRow: any = {}; // 选定的某条审核数据

    private instDataSourceList: any = []; // 信息表格所有数据

    private resultDataSource: any = []; // 结果表格显示数据

    private showEntryGroupModal: boolean = false; // 穿梭框

    private selectKeys: any[] = []; // 勾选值keys

    private calcDataIndex: number = 0; //

    layoutDialog: boolean = false;

    currentResultList: any[] = []; // 当前指令结果列表数据

    private resultDataSourceList: any[] = []; // 表格全部数据(前端分页)

    private filterResultTable: any[] = []; // 过滤表格数据(前端分页)

    private calcLoading: boolean = false;

    private loading: boolean = false; // 指令信息表格加载

    private resultLoading: boolean = false; // 指令结果表格加载

    private tadeP: any = {}; // 委托方向

    private marketIdP: any = {}; // 市场类型

    selectedFieldList = []; // 已选择字段列表

    showFieldList = []; // 要显示的表格列

    approveKey: number = -1;

    // 固定字段列表
    fixedFieldList = [
        { content: '指令序号', id: 'instNo', align: 'left' },
        { content: '恒生指令序号', id: 'dailyInstructionNo', minWidth: 130, align: 'left' },
    ];

    // 指令信息表格列
    private instColumns: any = this.ColumnUtil.handleColumns(
        [
            { content: '指令序号', id: 'instNo', align: 'left' },
            { content: '恒生指令序号', id: 'dailyInstructionNo', minWidth: 130, align: 'left' },
            { content: '审批序号', id: 'approverNoList', type: 'func', funcBody: value => value && value.toString(), align: 'left' },
            {
                content: '恒生审批状态',
                id: 'approveStatus',
                minWidth: 120,
                type: 'func',
                funcBody: value => value && this.approveStatusType[value],
                align: 'center',
            },
            { content: '审批结果', id: 'approveResult', type: 'func', funcBody: value => value && this.approveResultTrans[value], align: 'center' },
            { content: '审批人', id: 'approverName', align: 'center' },
            { content: '合规结果', id: 'complianceResult', type: 'statusTag', align: 'center' },
            { content: '产品名称', id: 'fundNameSt', align: 'center' },
            { content: '组合名称', id: 'fdAcName', align: 'center' },
            { content: '证券代码', id: 'stockCode', align: 'left' },
            { content: '证券名称', id: 'stockNameSt', minWidth: 120, align: 'center' },
            {
                content: '委托方向',
                id: 'realDirection',
                // type: 'status',
                // statusKV: this.tadeP,
                align: 'center',
            },
            { content: '指令价格', id: 'instPrice', type: 'func', funcBody: value => numberFormat(value, 2) || '--', align: 'right' },
            { content: '指令数量', id: 'instAmount', minWidth: 120, type: 'func', funcBody: value => numberFormat(value) || '--', align: 'right' },
            {
                content: '指令金额',
                id: 'instBalance',
                minWidth: 120,
                type: 'func',
                funcBody: value => numberFormat(value, 2) || '--',
                align: 'right',
            },
            { content: '全价价格', id: 'fullPrice', type: 'func', funcBody: value => numberFormat(value, 2) || '--', align: 'right' },
            { content: '全价金额', id: 'fullBalance', type: 'func', funcBody: value => numberFormat(value, 2) || '--', align: 'right' },
            { content: '金额单位', id: 'cc1', type: 'func', funcBody: value => (value ? value + '元' : '元'), align: 'right' },
            { content: '币种', id: 'curCode', align: 'right' },
            {
                content: '交易市场',
                id: 'marketCode',
                // type: 'status',
                // statusKV: this.marketIdP,
                align: 'center',
            },
            { content: '投资类型', id: 'investType', type: 'status', statusKV: this.Invest.investType, align: 'center' },
            {
                content: '存款利率',
                id: 'ratio',
                minWidth: 100,
                type: 'func',
                funcBody: value => (value != undefined ? numberFormat(value, 2) : '--'),
                align: 'right',
            },
            { content: '存款期限', id: 'poDayTerm', align: 'right' },
            {
                content: '通知天数',
                id: 'notifyDays',
                minWidth: 100,
                align: 'right',
            },
            {
                content: '回购到期日',
                id: 'repurDate',
                minWidth: 100,
                type: 'func',
                funcBody: value => dateFormat(value) || '--',
                align: 'center',
            },
            {
                content: '回购/拆借天数',
                id: 'repoDay',
                minWidth: 150,
                align: 'right',
            },
            {
                content: '交易对手',
                id: 'opponentCode',
                minWidth: 100,
                align: 'right',
            },
            {
                content: '下达人',
                id: 'direactUser',
                minWidth: 100,
                align: 'center',
            },
            {
                content: '下达时间',
                id: 'directDate',
                minWidth: 100,
                type: 'func',
                funcBody: value => dateFormat(value) || '--',
                align: 'center',
            },
            {
                content: '指令备注',
                id: 'summary',
                minWidth: 150,
                align: 'left',
            },
        ],
        'id',
        'fundNameSt',
        [{ content: '资产单元名称', id: 'assetName', width: 110, type: 'func', funcBody: value => value || '--' }]
    );

    exitAutoColumns = [
        // { content: '审批状态', id: 'approveStatus', type: 'func', funcBody: value => value && this.approveStatusType[value], align: 'center' },
        { content: '审批类型', id: 'approveType', type: 'func', funcBody: value => value && this.approveTypeTrans[value], align: 'center' },
    ];

    // 指令结果
    resultColumns = [
        { name: '产品代码', val: 'fundCode', sortable: true, align: 'left' },
        { name: '产品名称', val: 'fundNameSt', sortable: false, align: 'center' },
        { name: '证券代码', val: 'stockCode', sortable: true, align: 'left' },
        { name: '证券名称', val: 'stockNameSt', sortable: false, align: 'center' },
        { name: '条目编号', val: 'entryCode', sortable: true, align: 'left' },
        { name: '风险说明', val: 'entryName', sortable: false, align: 'left' },
        {
            name: '风险类型',
            val: 'entryType',
            minWidth: 100,
            sortable: false,
            type: 'func',
            funcBody: value => DictionConstUtil.EntryType[value],
            align: 'center',
        },
        {
            name: '风控阈值',
            val: 'thresholdValue',
            minWidth: 100,
            sortable: false,
            type: 'func',
            funcBody: (value, record) => (value != undefined ? numberFormat(value, record.unit) + unitShow(record.unit) : '--'),
            align: 'right',
        },
        {
            name: '比较方向',
            val: 'compareType',
            minWidth: 100,
            type: 'func',
            funcBody: value => DictionConstUtil.CompareDirection[value],
            align: 'center',
        },
        {
            name: '计算结果(单位)',
            val: 'calculateValue',
            minWidth: 150,
            sortable: false,
            type: 'func',
            funcBody: (value, record) => (this.WEB_DOCKING === 'CIBFUND' && value != undefined ? numberFormatXDAY(value, record.unit) + unitShow(record.unit) : value != undefined ? numberFormat(value, record.unit) + unitShow(record.unit) : '--'),
            align: 'right',
        },
        { name: '阈值类型', val: 'thresholdType', minWidth: 120, type: 'statusTag', sortable: true, align: 'center' },
        { name: '可投余量', val: 'investableBalance', minWidth: 140, sortable: false, align: 'right' },
        { name: '最大可交易量', val: 'maxTradable', minWidth: 175, sortable: false, align: 'right' },
        { name: '最大可交易量(汇总)', val: 'maxTradableMerge', minWidth: 175, sortable: false, align: 'right' },
        { name: '静态条目KEY', val: 'entryKey', minWidth: 150, sortable: false, align: 'left' },
        { name: '分支详情', val: 'branchCalculateResults', minWidth: 100, type: 'branchTag', sortable: false, align: 'center' },
    ];

    // 条目组配置
    private selectEntryGroupCode: any = {
        calculateEntryGroup: [],
        excludeEntryGroup: [],
    };

    // 历史审核条件
    searchParam = {
        fundCode: '',
        stockCode: '',
        directDate: '',
        entrustDirection: '',
        approveResult: '',
        approveStatus: '',
        approveType: '',
        approverCode: '',
        complianceResult: '',
    };

    // 指令结果信息
    private resultInfo = {
        result: '',
        date: '',
        count: '',
    };

    // 触警
    private thresholdTypeFilter: any = {
        '0': false,
        '1': true,
    };

    // 分页
    private pageInst: pages = {
        total: 0,
        currentPage: 1,
        pageSize: 10,
    };

    // 指令结果分页
    private pageResult: pages = {
        total: 0,
        currentPage: 1,
        pageSize: 10,
    };

    // 风险审核状态
    approveStatusType = {
        '0': '未审批',
        '1': '成功',
        '2': '失败',
        '3': '有警告',
    };

    // 审核类型
    // approveType = {
    //     '0': '空',
    //     '1': '自动审批',
    //     '2': '手工审批',
    // };

    // 审核结果
    // approveResult = {
    //     '0': '空',
    //     '1': '审批通过',
    //     '2': '审批拒绝',
    // };

    // 审核类型
    approveTypeTrans = {
        '0': '未审批',
        '1': '自动审批',
        '2': '手工审批',
    };

    // 审核结果
    approveResultTrans = {
        '0': '未审批',
        '1': '审批通过',
        '2': '审批拒绝',
    };

    TimeSendMessage = null;
    resourceCode: string = '';

    // 自动审批
    @Watch('isAutoApprove')
    handleAutoApprove() {
        this.$axios.post('systemParam/update', {
            paramKey: 'IS_AUTO_APPROVE',
            paramValue: this.isAutoApprove,
        });

        let items = (getSystem() || []).map(item => {
            if (item.paramKey == 'IS_AUTO_APPROVE') {
                item.paramValue = this.isAutoApprove;
            }
            return item;
        });

        UserModule.updateSystemParam(items);

        if (this.isAutoApprove) {
            this.TimeSendMessage && clearInterval(this.TimeSendMessage);
            let value = ((getSystem() || []).find(item => item.paramKey == 'AUTO_APPROVE_TIMING_INTERVAL') || {}).paramValue || false;
            // AUTO_APPROVE_TIMING_INTERVAL ---风险审批定时间隔，单位（分钟）,0为不轮询
            if (value && value !== '0') {
                this.TimeSendMessage = setInterval(() => {
                    this.getPassInstruction(false, 'autoRefresh');
                }, value * 60 * 1000);
            }
        }
    }

    beforeDestroy() {
        this.TimeSendMessage && clearInterval(this.TimeSendMessage);
        this.TimeSendMessage = null;
    }

    async mounted() {
        let data1 = [
            { name: '资产单元编号', val: 'assetCode', sortable: false, minWidth: 140 },
            { name: '资产单元名称', val: 'assetName', sortable: false, minWidth: 140 },
            { name: '组合编码', val: 'fundAccountCode', sortable: false, minWidth: 120 },
            { name: '组合名称', val: 'fdAcName', sortable: false, minWidth: 120 },
        ];
        this.resultColumns = this.ColumnUtil.handleResultColumns(this.resultColumns, 'val', data1);
        this.resourceCode = getActiveMenuCode().defaultActive;

        this.type == 'first' && this.getUserSelectEntryGroupList(this.resourceCode);

        // 委托方向
        this.tadeP = DictionConstUtil.ListToPojo(await DictionConstUtil.FNTradeDirection());

        // 市场类型
        this.marketIdP = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());

        await this.queryLayout();

        this.getPassInstruction();

        this.isFirst = false;
    }

    // 获取页面布局信息
    async queryLayout() {
        this.loading = true;
        let url = this.type === 'history' ? 'TN_INST_APPRPVAL_HISTORY' : 'TN_INST_APPRPVAL';
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/' + url)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        let keys = this.fixedFieldList.map(item => item.id);
        let list = this.existAutoApprove == '1' ? this.exitAutoColumns.concat(this.instColumns) : this.instColumns;
        if (!resList) {
            // 新用户初始化
            this.selectedFieldList = list.filter(item => !keys.includes(item.id));
        } else {
            this.selectedFieldList = [];
            if (resList.length) {
                JSON.parse(resList).forEach(item => {
                    let obj = list.find(ele => ele.content === item.content); //
                    if (obj) {
                        this.selectedFieldList.push(obj);
                    }
                });
            }
        }
        this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        this.approveKey++;
        this.loading = false;
    }

    // 页面布局回调
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 后端分页(指令信息)
    private pageQueryInst(): void {
        this.getPassInstruction();
    }

    // 获取指令信息
    async getPassInstruction(refresh?: boolean, operateType?: string) {
        let url = this.type == 'history' ? '/instruction/history/bypass/list' : '/instruction/bypass/list/v1';
        let param = this.type == 'history' ? { ...this.searchParam, paging: this.pageInst } : { paging: this.pageInst };
        this.loading = true;
        let needValue = this.selectKeys[0];
        let temp = await new Promise((resolve, reject) => {
            // this.$axios
            //     .post(url, param)
            this.$axios({ url: url, method: 'post', data: param, headers: { operateType: operateType } })
                .then((res: any) => {
                    let res1 = res.list || [];
                    this.pageInst.total = res.total;
                    // 试算有问题或恒生转入数据
                    let d1 = res1.filter(item => !item.complianceResult);
                    // 正常数据
                    let d2 = res1.filter(item => !!item.complianceResult);

                    // d1.sort((a, b) => a.instNo.replace(/[^0-9]/gi, '') - b.instNo.replace(/[^0-9]/gi, ''));
                    // d2.sort((a, b) => a.instNo.replace(/[^0-9]/gi, '') - b.instNo.replace(/[^0-9]/gi, ''));

                    d2.forEach(item => (item.disableRow = true));
                    // this.selectKeys = d1.map(item => item.instNo);
                    this.instDataSourceList = d1.concat(d2);
                    this.loading = false;
                    resolve(res);
                })
                .catch(err => {
                    this.loading = false;
                    reject(err);
                });
        });

        // 有值时
        if (this.instDataSourceList[0]) {
            if (refresh) {
                // 刷新页面
                let index = this.instDataSourceList.findIndex(item => item.instNo == needValue) || 0;
                let record = this.instDataSourceList[index];
                this.handleRow({ row: record });
                this.selectKeys = [];
                (this.$refs as any).xTable1.setCurrentRow(this.instDataSourceList[index]);
            } else {
                this.handleRow({ row: this.instDataSourceList[0] });
                (this.$refs as any).xTable1.setCurrentRow(this.instDataSourceList[0]);
            }
        } else {
            this.resultInfo = {
                result: '',
                date: '',
                count: '',
            };
            this.resultDataSourceList = [];
            this.filterResultTable = [];
            this.pageQueryResult(1);
        }
    }

    // 按钮点击
    private handleShowSetting(action: string, btype?: boolean) {
        if (action === 'setting') {
            this.showEntryGroupModal = true;
        } else if (action === 'start') {
            if (!this.instDataSourceList || !this.instDataSourceList.length || !this.selectKeys || !this.selectKeys.length) {
                this.yh_message_warn('未选择指令进行计算');
                return;
            }
            // byte为false时
            if (!btype) {
                // 计算前对指令进行重新排序 并设置重新计算规则
                let d1 = this.instDataSourceList.filter(item => !item.complianceResult);
                let d2 = this.instDataSourceList.filter(item => !!item.complianceResult);
                d1.sort((a, b) => a.instNo.replace(/[^0-9]/gi, '') - b.instNo.replace(/[^0-9]/gi, ''));
                d2.sort((a, b) => a.instNo.replace(/[^0-9]/gi, '') - b.instNo.replace(/[^0-9]/gi, ''));
                d1.forEach(item => (item.disableRow = false));
                d2.forEach(item => (item.disableRow = true));
                this.instDataSourceList = d1.concat(d2);
                this.calcDataIndex = 0;
            }

            this.calcLoading = true;

            let requestData = [];
            for (; this.calcDataIndex < this.instDataSourceList.length; this.calcDataIndex++) {
                let instruction = this.instDataSourceList[this.calcDataIndex];
                // 数据问题或者未勾选的
                if (!this.selectKeys.includes(instruction.instNo)) {
                    continue;
                } else {
                    requestData.push({
                        outOrderCode: instruction.outOrderCode,
                        requestId: UUID() + '-' + new Date().getTime(),
                        instructionType: '',
                        orderType: '8',
                        calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
                        excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
                        instructionNo: instruction.instNo,
                        dailyInstructionNo: instruction.dailyInstructionNo,
                    });
                }
            }

            this.$axios
                .post('/dataEngine/multi/byPass/startTrial', requestData)
                .then((res: any) => {
                    // 满足条件进行下一步审核
                    // if (
                    //     Number(res.thresholdType) > 0 &&
                    //     this.instDataSourceList[this.calcDataIndex] &&
                    //     !this.instDataSourceList[this.calcDataIndex].complianceResult
                    // ) {
                    //     this.$confirm(
                    //         '是否该指标忽略，点击【忽略】，则继续风险计算，点击【不忽略】，则风控停止计算，可重新发起风险计算',
                    //         DictionConstUtil.ThresholdType[res.thresholdType] + '[指令序号：' + instruction.instNo + ']',
                    //         {
                    //             confirmButtonText: '不忽略',
                    //             cancelButtonText: '忽略',
                    //             type: 'warning',
                    //         }
                    //     )
                    //         .then(() => {
                    //             this.calcLoading = false;
                    //         })
                    //         .catch(() => {
                    //             this.handleShowSetting('start', true);
                    //         });
                    // }
                    this.yh_message_success('风险计算成功');
                })

                .finally(() => {
                    this.getPassInstruction(true);
                    this.calcLoading = false;
                });
        } else if (action === 'approve') {
            if (!this.instDataSourceList || !this.instDataSourceList.length || !this.selectKeys || !this.selectKeys.length) {
                this.yh_message_warn('未选择指令进行审核');
                return;
            }
            // byte为false时
            if (!btype) {
                // 计算前对指令进行重新排序 并设置重新计算规则
                let d1 = this.instDataSourceList.filter(item => !item.complianceResult);
                let d2 = this.instDataSourceList.filter(item => !!item.complianceResult);
                d1.sort((a, b) => a.instNo.replace(/[^0-9]/gi, '') - b.instNo.replace(/[^0-9]/gi, ''));
                d2.sort((a, b) => a.instNo.replace(/[^0-9]/gi, '') - b.instNo.replace(/[^0-9]/gi, ''));
                d1.forEach(item => (item.disableRow = false));
                d2.forEach(item => (item.disableRow = true));
                this.instDataSourceList = d1.concat(d2);
                this.calcDataIndex = 0;
            }

            this.calcLoading = true;

            let requestData = [];
            for (; this.calcDataIndex < this.instDataSourceList.length; this.calcDataIndex++) {
                let instruction = this.instDataSourceList[this.calcDataIndex];
                // 数据问题或者未勾选的
                if (!this.selectKeys.includes(instruction.instNo)) {
                    continue;
                } else {
                    requestData.push({
                        outOrderCode: instruction.outOrderCode,
                        requestId: UUID() + '-' + new Date().getTime(),
                        instructionType: '',
                        orderType: '8',
                        calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
                        excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
                        instructionNo: instruction.instNo,
                        dailyInstructionNo: instruction.dailyInstructionNo,
                    });
                }
            }

            this.$axios
                .post('/dataEngine/mutli/byPass/startApprove', requestData)
                .then((res: any) => {
                    this.yh_message_success('风险审核成功');
                })
                .finally(() => {
                    this.getPassInstruction(true);
                    this.calcLoading = false;
                });
        } else if (action === 'refresh') {
            this.getUserSelectEntryGroupList(this.resourceCode);
            this.calcDataIndex = 0;
            (this.$refs['xTable1'] as any).clearCheckboxRow();
            this.getPassInstruction();
        }
    }

    // 穿梭框返回值
    private transReturn(obj): void {
        if (obj.action === 'confirm') {
            this.selectEntryGroupCode = obj.data;
        }
        this.showEntryGroupModal = false;
    }

    // 获取用户配置组信息
    private getUserSelectEntryGroupList(key: string): void {
        this.$axios.get('/entry/group/user/select/list/' + key).then((res: any) => {
            res = res || [];
            this.selectEntryGroupCode = {
                calculateEntryGroup: res.filter(item => item.instGroupType === '1' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
                excludeEntryGroup: res.filter(item => item.instGroupType === '2' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
            };
        });
    }

    // 筛选条件事件
    private handelThresholdTypeFilter() {
        this.filterResultTable = this.resultDataSourceList.filter(
            item => (this.thresholdTypeFilter['1'] && item.thresholdType !== '0') || (this.thresholdTypeFilter['0'] && item.thresholdType === '0')
        );
        this.pageQueryResult(1);
    }

    // 点击表行回调
    async handleRow(el: any) {
        // 点击勾选不生效
        if (el.triggerCheckbox) {
            return;
        }

        let record = el.row;
        let url = this.type == 'history' ? '/instruction/history/inst/last/entry/result/' : '/instruction/inst/last/entry/result/';

        this.resultLoading = true;
        let re: any = await new Promise((resolve, reject) => {
            this.$axios
                .get(url + record.outOrderCode)
                .then((res: any) => {
                    console.log(res, 'res');
                    this.currentResultList = res;
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        this.resultInfo.result = record.complianceResult;
        this.resultInfo.date = (dateFormat(record.approveDate) + ' ' + timeFormat(record.approveTime)).trim() || '--';
        this.handleResultData(re);
        this.resultLoading = false;
    }

    // 指令结果总数据处理
    handleResultData(re) {
        this.resultDataSourceList = re;
        this.resultInfo.count = re.length;
        this.filterResultTable = re;
        this.handelThresholdTypeFilter();
    }

    // 勾选数据
    private handleChecked({ selection }): void {
        this.selectKeys = XEUtils.map(selection, item => item.instNo);
    }

    // 全部勾选
    handleCheckedAll({ selection }) {
        this.selectKeys = XEUtils.map(selection, item => item.instNo);
    }

    // 前端分页(指令结果)
    private pageQueryResult(curPage?: number): void {
        if (curPage) {
            this.pageResult.currentPage = curPage;
        }
        let list = this.filterResultTable;
        this.pageResult.total = list.length;
        this.resultDataSource = getCurrentPageData(list, this.pageResult.currentPage, this.pageResult.pageSize);
    }

    // 查询条件按钮
    handleButton(type): void {
        if (type == 'search') {
            this.pageQueryInst();
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        }
    }

    // 获取对象长度
    getObjectLength(obj) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    // 获取可投余量、最大可交易量名称
    getShowName(name: string) {
        if (name == 'investableBalance') {
            return '可投余量';
        } else if (name == 'maxTradable') {
            return '最大可交易量';
        } else if (name == 'maxTradableMerge') {
            return '最大可交易量(汇总)';
        }
    }

    // 获取字段名
    getParamName(name: string) {
        return name == 'investableBalance' ? 'INVESTABLE_BALANCE_' : name == 'maxTradable' ? 'MAX_TRADABLE_' : 'MAX_TRADABLE_';
    }

    // 是否可勾选
    checkMethod({ row }) {
        return row.approveStatus != '1';
    }

    // disableRow字段置灰
    getRowStyle({ row }) {
        if (row.disableRow) {
            return { height: '35px', backgroundColor: '#cfcfcf' };
        } else {
            return { height: '35px' };
        }
    }

    // cell样式处理
    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.exitAutoColumns.concat(this.instColumns).find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    // 字段左右居中处理-暂时无用
    getAlign(ele) {
        let obj = this.exitAutoColumns.concat(this.instColumns).find(item => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }

    // 指令结果cell样式处理
    getCellStyleResult({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.resultColumns.find(item => item.val == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    // 结果字段对齐
    getAlignResult(ele) {
        console.log(ele);
        let obj = this.resultColumns.find(item => item.val == ele.val);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
#inst-approval {
    min-width: 1000px;
    overflow: auto;
    padding: 6px 10px;
    .title {
        font-weight: 700;
        display: block;
    }
    .title2 {
        margin-top: 10px;
    }
    .auto-select {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .setting {
            font-size: 30px;
            cursor: pointer;
        }
    }

    #main-content {
        border: 1px solid #cacaca;
        padding: 10px 10px 0 10px;
        margin-top: 6px;
    }
    #bottom-content {
        display: flex;
        justify-content: space-between;
        margin: 10px 0;
    }
}
/deep/ .el-divider--horizontal {
    margin: 6px 0;
}
/deep/ .el-pagination {
    padding: 6px 6px 6px 0 !important;
}
/deep/ .vxe-table {
    .vxe-sort--asc-btn.sort--active,
    .vxe-sort--desc-btn.sort--active {
        color: #409eff !important;
    }
    .vxe-body--row.row--current {
        background-color: #a8d4f7 !important;
    }
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(50vh - 197px);
    }
}

// 表头加粗
/deep/ .vxe-header--column.col--ellipsis > .vxe-cell .vxe-cell--title {
    font-weight: bolder;
}
</style>
